<template>
  <div class="impact-container">
    <div class="header">
      <button class="nav-button" @click="goToPreviousStep">上一步</button>
      <div class="steps-container">
        <div v-for="(step, index) in steps" :key="step" :class="['step-box', { active: index === 1 }]">
          {{ step }}
        </div>
      </div>
      <button class="nav-button" @click="goToNextStep">下一步</button>
    </div>

    <div class="table-container">
      <div class="table-header">
        <span class="table-title">工序流程清单</span>
        <div class="header-buttons">
          <el-button type="primary" link :icon="Setting" @click="openCalcParamsWindow">选择碳排放因子</el-button>
        </div>
      </div>
      <el-table :data="tableData" style="width: 100%" border :span-method="objectSpanMethod">
        <!-- 生产活动 -->
        <el-table-column prop="activityName" label="生产活动" width="220" fixed="left">
          <template #default="{ row }">
            <div class="activity-cell">
              <el-icon><Box /></el-icon>
              <span>{{ getActivityName(row.objectName, row.objectType) }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 单元过程 -->
        <el-table-column prop="processName" label="单元过程名称" width="220" fixed="left">
          <template #default="{ row }">
            <div class="process-cell">
              <el-icon><Operation /></el-icon>
              <span>{{ row.processName || "——" }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 所属设备 -->
        <el-table-column prop="equipmentName" label="所属设备" width="220">
          <template #default="{ row }">
            <div class="equipment-cell">
              <el-icon><Monitor /></el-icon>
              <span>{{ row.equipmentName || "——" }}</span>
            </div>
          </template>
        </el-table-column>

        <!-- 输入/输出类型 -->
        <el-table-column label="输入/输出" width="220" align="center">
          <template #default="{ row }">
            <div class="io-type">
              <div :class="['io-item', row.type === '——' ? 'empty' : row.type]">
                {{ row.type === "input" ? "输入" : row.type === "output" ? "输出" : "——" }}
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 碳排放源 -->
        <el-table-column label="碳排放源" min-width="220" align="center">
          <template #default="{ row }">
            <div class="emission-sources">
              <div class="source-wrapper">
                <span class="source-type">
                  {{ row.type === "input" ? getEmissionSourceLabel(row.label) : row.label || "——" }}
                </span>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 用量 -->
        <el-table-column label="用量" min-width="220" align="center">
          <template #default="{ row }">
            <div class="consumption-wrapper">
              <div class="consumption-item">
                <span class="amount">
                  {{ row.consumption || "——" }}
                </span>
                <span class="unit">{{ getIOUnitLabel(row.unit) }}</span>
                <template v-if="row.dataSource === '分配获取'"> （总{{ row.processName }}） </template>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 计算参数配置弹窗 -->
    <el-dialog
      v-model="calcParamsVisible"
      title="选择碳排放因子"
      :width="'70%'"
      class="calc-params-dialog"
      :close-on-click-modal="false"
    >
      <el-table :data="energyFactors" border>
        <el-table-column label="能源类型" width="500">
          <template #default="{ row }">
            {{ row.label }}
          </template>
        </el-table-column>
        <el-table-column label="碳排放因子" min-width="200">
          <template #default="{ row }">
            <div class="factor-select">
              <span v-if="row.selectedFactor" class="selected-factor">
                {{ formatFactorLabel(getSelectedFactorDetails(row.selectedFactor)) }}
              </span>
              <span v-else class="no-factor">未选择</span>
              <el-button type="primary" link @click="openFactorDialog(row)">
                {{ row.selectedFactor ? "修改" : "选择" }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="calcParamsVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCalcParams">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 因子选择弹窗 -->
    <el-dialog
      v-model="factorDialogVisible"
      :title="`选择${currentEnergyType?.label || ''}的碳排放因子`"
      width="1500px"
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="custom-dialog"
      @close="handleFactorDialogClose"
    >
      <div class="factor-details">
        <el-input
          v-model="searchFactor"
          size="small"
          placeholder="请输入因子名称"
          clearable
          :prefix-icon="Search"
          style="margin-bottom: 20px"
        />
        <el-table
          :data="filteredFactors"
          style="width: 100%"
          max-height="400px"
          border
          :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            height: '50px',
            fontWeight: 600
          }"
          :cell-style="{
            height: '45px'
          }"
        >
          <el-table-column prop="factorId" label="因子编号" width="120" show-overflow-tooltip />
          <el-table-column label="因子名称" min-width="180" show-overflow-tooltip>
            <template #default="{ row: factor }">
              <span class="factor-label">{{ factor.factorLabel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="因子类型" width="110" show-overflow-tooltip>
            <template #default="{ row: factor }">
              {{ getFactorTypeLabel(factor.factorName) }}
            </template>
          </el-table-column>
          <el-table-column prop="factorValue" label="因子数值" width="110" show-overflow-tooltip />
          <el-table-column label="因子单位" width="150" show-overflow-tooltip>
            <template #default="{ row: factor }">
              {{ getFactorUnitLabel(factor.factorUnit) }}
            </template>
          </el-table-column>
          <el-table-column label="地域代表性" width="130" show-overflow-tooltip>
            <template #default="{ row: factor }">
              {{ getRegionLabel(factor.region) }}
            </template>
          </el-table-column>
          <el-table-column prop="source" label="数值来源" min-width="200" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="200" show-overflow-tooltip />
          <el-table-column align="center" label="操作" width="150" fixed="right" class-name="operation-column">
            <template #default="{ row: factor }">
              <el-button type="primary" link :disabled="currentRow?.selectedFactor === factor.id" @click="selectFactor(factor)">
                <el-icon><CirclePlus /></el-icon>
                {{ currentRow?.selectedFactor === factor.id ? " 已选择" : " 选择" }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import { Box, Operation, Monitor, Setting, Search, CirclePlus } from "@element-plus/icons-vue";
import { factorType, unitType, regionType, IOUnitType } from "@/utils/serviceDict";
import { useRoute, useRouter } from "vue-router";
import axios from "axios";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();

const route = useRoute();
const router = useRouter();
const steps = ref(["分配参数配置", "选择碳排放因子", "碳足迹计算结果"]);
const baseUrl = import.meta.env.VITE_BASE_URL;

const equipmentNameMap = ref<Record<number, string>>({});

// 拉取所有设备并建立映射（id -> name）
const fetchEquipments = async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
  const userId = Number(userInfo.id) || 0;

  try {
    const res = await axios.post(`${baseUrl}/api/carbon/getAllEquipments`, { userId });
    if (res.data?.code === 200) {
      const list = res.data.data || [];
      list.forEach((item: any) => {
        equipmentNameMap.value[item.id] = item.equipmentName;
      });
    }
  } catch (err) {
    console.error("获取设备列表失败", err);
  }
};
// 计算参数配置相关
const calcParamsVisible = ref(false);

// 能源类型和对应的因子
const energyFactors = ref([
  ...factorType.map(factor => ({
    energyType: factor.value,
    selectedFactor: null as string | null,
    label: factor.label
  }))
]);

interface EmissionFactor {
  id: string;
  factorName: number;
  factorLabel: string;
  factorValue: number;
  factorUnit: number | string;
  region: number;
  [key: string]: any;
}
const emissionFactorList = ref<EmissionFactor[]>([]);

// 获取排放因子数据
const fetchEmissionFactors = async () => {
  try {
    const res = await axios.get(`${baseUrl}/api/carbon/getAllFactors`);
    if (res.data?.code === 200) {
      emissionFactorList.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || "获取排放因子数据失败");
    }
  } catch (error) {
    console.error("获取排放因子数据出错:", error);
    ElMessage.error("获取排放因子数据失败");
  }
};

// 获取因子单位标签
const getFactorUnitLabel = (unitValue: string | number) => {
  // 处理后端返回的字符串类型或数字类型
  const value = typeof unitValue === "string" ? parseInt(unitValue, 10) : unitValue;
  const unit = unitType.find(u => u.value === value);
  return unit ? unit.label : unitValue;
};

// 获取输入输出单位标签
const getIOUnitLabel = (unitValue: number) => {
  const unit = IOUnitType.find(u => u.value === unitValue);
  return unit ? unit.label : "";
};

// 获取排放源标签
const getEmissionSourceLabel = (type: number) => {
  const source = factorType.find(f => f.value === type);
  return source ? source.label : type;
};

// 上一步
const goToPreviousStep = () => {
  const projectId = route.params.projectId;
  const needAllocation = localStorage.getItem(`needAllocation_${projectId}`) === "true";

  if (needAllocation) {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push(`/lca/impact/allocation/${projectId}`);
  } else {
    if (route.meta.isAffix) return;
    tabStore.removeTabs(route.fullPath);
    router.push(`/lca/inventory/materialIndex/${projectId}`);
  }
};

// 下一步跳转
const goToNextStep = async () => {
  const projectId = route.params.projectId as string;

  // 2. 检查所有能源类型是否都选择了碳排因子
  const unselectedFactors = energyFactors.value.filter(factor => !factor.selectedFactor);
  if (unselectedFactors.length > 0) {
    ElMessage.warning(`请为以下能源类型选择碳排因子：${unselectedFactors.map(f => f.label).join("、")}`);
    calcParamsVisible.value = true;
    return;
  }

  try {
    // 准备请求参数
    const requestData = {
      projectId: Number(projectId),
      factors: energyFactors.value.map(factor => {
        const factorDetails = getSelectedFactorDetails(factor.selectedFactor || "");
        return {
          energyType: factor.energyType,
          selectedFactor: factor.selectedFactor,
          label: factor.label,
          factorValue: factorDetails?.factorValue || 0
        };
      })
    };

    // 调用计算接口
    const calcResponse = await axios.post(`${baseUrl}/api/carbon/calculateNodePCF`, requestData);

    if (calcResponse.data.code !== 200) {
      throw new Error(calcResponse.data.msg || "计算失败");
    }

    ElMessage.success("PCF计算完成");
  } catch (error: any) {
    console.error("PCF计算失败:", error);
    ElMessage.error(`PCF计算失败: ${error.message}`);
    return;
  }
  console.log("energyFactors.value:", energyFactors.value);
  const result: { [key: string]: number } = {};

  // 创建因子类型到因子值的映射
  const queryPcfKey = `PCF_values_${projectId}`;
  const savedPcf = localStorage.getItem(queryPcfKey);
  console.log("savedPcf:", savedPcf ? JSON.parse(savedPcf) : null);
  const res = await axios.get(baseUrl + `/api/carbon/getCarbonEmissionsSubValueById?projectId=${projectId}`);
  console.log("外购零部件碳排放值收集:", res.data.data);
  let totalPCFvalue = 0;
  if (res.data.data) {
    const Pcf = res.data.data;
    totalPCFvalue = Pcf.reduce((total: any, material: any) => {
      //将 PCFvalue 转换为数字并累加
      return total + parseFloat(material.PCFvalue);
    }, 0);
  }
  const paramsData = {
    dianValue: result["1"]?.toString() || "0",
    shuiValue: result["2"]?.toString() || "0",
    qiValue: result["3"]?.toString() || "0",
    youValue: result["4"]?.toString() || "0",
    dianFactor: "0.5568",
    shuiFactor: "0.5992",
    qiFactor: "2.146",
    youFactor: "2.86",
    materPcf: totalPCFvalue.toString()
  };

  const resData = {
    pcfTotal: ""
  };
  axios.post(baseUrl + "/api/carbon/calculatePcf", paramsData).then(res => {
    console.log(res.data);
    ElMessage;
    resData.pcfTotal = res.data.TotalPcf;
    const pcfKey = `pcfData_${projectId}`;
    localStorage.setItem(pcfKey, JSON.stringify(resData));
  });
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/impact/dataResults/${projectId}`);
};

const fetchFlowChartList = async () => {
  try {
    const projectId = route.params.projectId;
    const res = await axios.get(`${baseUrl}/api/carbon/getAllFlowcharts`, {
      params: { projectId }
    });
    if (res.data?.code === 200) {
      const allData = res.data.data || [];
      const manufacturingData = allData.filter((item: { objectType: string }) => item.objectType !== "0");
      const assemblyData = allData.filter((item: { objectType: string }) => item.objectType === "0");
      return [...manufacturingData, ...assemblyData];
    } else {
      ElMessage.error(res.data.msg || "获取流程图失败");
      return [];
    }
  } catch (error) {
    console.error("获取流程图出错:", error);
    ElMessage.error("获取流程图失败");
    return [];
  }
};

interface FlowChartItem {
  projectId: number;
  objectId: string;
  objectType: string;
  nodes: Array<{
    nodeId: string;
    process: {
      processName: string;
    };
    equipments?: Array<{ equipmentId: number; ratio?: number }>;
    equipmentName: string;
    inputNodes?: Array<{
      inputType: number;
      inputConsumption: number;
      inputUnit: number;
      dataSource: string;
      equipmentId?: number; // Added equipmentId to inputNodes
    }>;
    outputNodes?: Array<{
      outputName: string;
      outputConsumption: number;
      outputUnit: number;
      equipmentId?: number; // Added equipmentId to outputNodes
    }>;
  }>;
}

const flowChartData = ref<FlowChartItem[]>([]);

// 转换数据结构
const tableData = computed(() => {
  const rows: any[] = [];
  flowChartData.value.forEach(flowChart => {
    flowChart.nodes.forEach(node => {
      // 如果节点没有显式设备列表，则创建一个虚拟设备占位，equipmentId 为 undefined
      const equipmentsArray =
        node.equipments && node.equipments.length ? node.equipments : [{ equipmentId: undefined } as { equipmentId?: number }];

      equipmentsArray.forEach(eq => {
        const equipName = eq.equipmentId
          ? equipmentNameMap.value[eq.equipmentId] || `设备${eq.equipmentId}`
          : (node as any).equipmentName || "——";

        // 过滤与该设备相关的输入 / 输出节点
        const relateInputs = (node.inputNodes || []).filter(input => (input.equipmentId ?? eq.equipmentId) === eq.equipmentId);
        const relateOutputs = (node.outputNodes || []).filter(
          output => ((output as any).equipmentId ?? eq.equipmentId) === eq.equipmentId
        );

        // 若相关输入/输出均为空，则仍添加空行
        if (!relateInputs.length && !relateOutputs.length) {
          rows.push({
            objectId: flowChart.objectId,
            objectType: flowChart.objectType,
            objectName: flowChart.objectName,
            processName: node.process.processName,
            equipmentName: equipName,
            type: "——",
            label: "——",
            consumption: "——",
            unit: "——"
          });
        }

        // 输入行
        relateInputs.forEach(input => {
          rows.push({
            objectId: flowChart.objectId,
            objectType: flowChart.objectType,
            objectName: flowChart.objectName,
            processName: node.process.processName,
            equipmentName: equipName,
            type: "input",
            label: input.inputType,
            consumption: input.inputConsumption,
            unit: input.inputUnit,
            dataSource: input.dataSource
          });
        });

        // 输出行
        relateOutputs.forEach(output => {
          rows.push({
            objectId: flowChart.objectId,
            objectType: flowChart.objectType,
            objectName: flowChart.objectName,
            processName: node.process.processName,
            equipmentName: equipName,
            type: "output",
            label: output.outputName,
            consumption: output.outputConsumption,
            unit: output.outputUnit
          });
        });
      });
    });
  });
  return rows;
});

onMounted(async () => {
  const projectId = route.params.projectId as string;
  // 先拉取设备映射
  await fetchEquipments();
  // 获取流程图数据并直接用于表格显示
  flowChartData.value = await fetchFlowChartList();
  console.log("从后端读取flowChartData:", flowChartData.value);

  // 获取排放因子数据
  await fetchEmissionFactors();

  // 尝试从 localStorage 加载已保存的参数
  const key = `calcParams_${projectId}`;
  const savedParams = localStorage.getItem(key);
  console.log("savedParams:", savedParams);
  if (savedParams) {
    try {
      const params = JSON.parse(savedParams);
      params.slice(1).forEach((param: { factorType: number; factorId: string }) => {
        const factor = energyFactors.value.find(f => f.energyType === param.factorType);
        if (factor) {
          factor.selectedFactor = param.factorId;
        }
      });
    } catch (error) {
      console.error("加载已保存的计算参数失败:", error);
    }
  }
});

// 保存计算参数
const saveCalcParams = () => {
  const projectId = route.params.projectId as string;
  // 保存所有能源类型的选择
  const params = [
    { projectId },
    ...energyFactors.value.map(factor => ({
      factorType: factor.energyType,
      factorId: factor.selectedFactor
    }))
  ];
  localStorage.setItem(`calcParams_${projectId}`, JSON.stringify(params));
  calcParamsVisible.value = false;
};

// 打开计算参数配置窗口
const openCalcParamsWindow = () => {
  const projectId = route.params.projectId as string;
  calcParamsVisible.value = true;
  // 尝试从 localStorage 加载已保存的参数
  const key = `calcParams_${projectId}`;
  const savedParams = localStorage.getItem(key);
  if (savedParams) {
    try {
      const params = JSON.parse(savedParams);
      // 跳过第一个元素（projectId），遍历剩余的因子配置
      params.slice(1).forEach((param: { factorType: number; factorId: string }) => {
        const factor = energyFactors.value.find(f => f.energyType === param.factorType);
        // 判断该因子id是否还在后端返回的因子列表中
        const exists = emissionFactorList.value.some(f => String(f.id) === String(param.factorId));
        if (factor) {
          factor.selectedFactor = exists ? param.factorId : null;
        }
      });
    } catch (error) {
      console.error("加载已保存的计算参数失败:", error);
    }
  } else {
    // 没有保存时全部置空
    energyFactors.value.forEach(factor => {
      factor.selectedFactor = null;
    });
  }
};

// 获取地区标签
const getRegionLabel = (region: number) => {
  const regionItem = regionType.find(r => r.value === region);
  return regionItem ? regionItem.label : region;
};

// 根据能源类型获取对应的排放因子列表
const getFactorsByType = (energyType: number) => {
  return emissionFactorList.value.filter(factor => factor.factorName === energyType);
};

// 格式化因子显示标签
const formatFactorLabel = (factor: any) => {
  if (!factor) return "";
  const value = typeof factor.factorUnit === "string" ? parseInt(factor.factorUnit, 10) : factor.factorUnit;
  const unitItem = unitType.find(u => u.value === value);
  return `${factor.factorValue} ${unitItem?.label || factor.factorUnit}`;
};

// 处理因子选择变化
const handleFactorChange = (row: any) => {
  const selectedFactor = emissionFactorList.value.find(f => f.id === row.selectedFactor);
  console.log("选择的因子:", selectedFactor);
};

// 获取因子类型标签
const getFactorTypeLabel = (type: number) => {
  const factor = factorType.find(f => f.value === type);
  return factor ? factor.label : type;
};

// 选择因子
const selectFactor = (factor: any) => {
  if (currentRow.value) {
    currentRow.value.selectedFactor = factor.id;
    handleFactorChange(currentRow.value);
    factorDialogVisible.value = false;
  }
};

// 打开因子选择弹窗
const openFactorDialog = (row: any) => {
  currentRow.value = row;
  currentEnergyType.value = factorType.find(f => f.value === row.energyType);
  currentFactors.value = getFactorsByType(row.energyType);
  factorDialogVisible.value = true;
};

// 获取选中因子的详细信息
const getSelectedFactorDetails = (factorId: string) => {
  return emissionFactorList.value.find(f => f.id === factorId);
};

const factorDialogVisible = ref(false);
const currentRow = ref<any>(null);
const currentEnergyType = ref<any>(null);
const currentFactors = ref<any[]>([]);

const searchFactor = ref("");
const filteredFactors = computed(() => {
  if (!currentFactors.value) return [];
  return currentFactors.value.filter(factor => factor.factorLabel.toLowerCase().includes(searchFactor.value.toLowerCase()));
});

const handleFactorDialogClose = () => {
  searchFactor.value = ""; // 清空搜索框
};

// 获取生产活动名称
const getActivityName = (objectName: string, objectType: string) => {
  return objectType === "0" ? objectName : `${objectName}制造`;
};

// 修改单元格合并方法
const objectSpanMethod = ({ row, rowIndex, columnIndex }: { row: any; rowIndex: number; columnIndex: number }) => {
  // 仅合并前两列，其余列不合并
  if (columnIndex > 1) {
    return { rowspan: 1, colspan: 1 };
  }

  const prevRow = tableData.value[rowIndex - 1];

  // 计算需要合并的行数
  const getSpanCount = (condition: boolean) => {
    if (!condition) return { rowspan: 0, colspan: 0 };

    let count = 0;
    for (let i = rowIndex; i < tableData.value.length; i++) {
      const currentRow = tableData.value[i];
      const isSameGroup =
        columnIndex === 0
          ? currentRow.objectId === row.objectId
          : currentRow.processName === row.processName && currentRow.objectId === row.objectId;

      if (!isSameGroup) break;
      count++;
    }
    return { rowspan: count, colspan: 1 };
  };

  // 生产活动列
  if (columnIndex === 0) {
    return getSpanCount(!prevRow || prevRow.objectId !== row.objectId);
  }

  // 单元过程列
  return getSpanCount(!prevRow || prevRow.processName !== row.processName || prevRow.objectId !== row.objectId);
};
</script>

<style scoped>
/* 基础布局样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.nav-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
.nav-button:hover {
  background-color: #007d6a;
}
.steps-container {
  display: flex;
  justify-content: space-between;
  width: 80%;
  padding: 0 20px;
}
.step-box {
  position: relative;
  flex: 1;
  padding: 15px 10px;
  margin: 0 10px;
  color: #777777;
  text-align: center;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s;
}
.step-box.active {
  font-weight: bold;
  color: #009688;
  background-color: #e6f5f3;
  border-color: #009688;
}

/* 确保非活动状态的步骤显示为默认样式 */
.step-box:not(.active) {
  color: #777777;
  background-color: #f9f9f9;
  border-color: #dcdcdc;
}
.step-box::after {
  position: absolute;
  top: 50%;
  right: -20px;
  font-size: 20px;
  color: #009688;
  content: "→";
  transform: translateY(-50%);
}
.step-box:last-child::after {
  visibility: hidden;
}
.table-container {
  padding: 20px;
  margin-top: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

/* 表格基础样式 */
:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-color-primary-light-9);
  --el-table-row-hover-bg-color: var(--el-color-primary-light-9);
  --el-table-row-height: auto;
  --el-table-padding: 12px;
}
:deep(.el-table__cell) {
  padding: 12px !important;
}
:deep(.el-table th) {
  font-weight: 600;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}
:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: var(--el-color-primary-light-9);
}

/* 表格单元格内容样式 */
.process-cell,
.equipment-cell {
  display: flex;
  gap: 8px;
  align-items: center;
}
.io-type {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.io-item {
  display: inline-block;
  padding: 4px 12px;
  font-size: 13px;
  text-align: center;
  border-radius: 4px;
}
.io-item.input {
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-5);
}
.io-item.output {
  color: var(--el-color-success);
  background-color: var(--el-color-success-light-9);
  border: 1px solid var(--el-color-success-light-5);
}

/* 弹窗样式 */
.calc-params-dialog :deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  max-height: 80vh;
}
.calc-params-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
}
.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

/* 添加生产活动单元格样式 */
.activity-cell {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 4px 0;
}
.activity-cell .el-icon {
  color: var(--el-color-warning);
}
</style>
